package com.epam.traning.taskmanager.auth;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.Uri;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;

public class VkOAuthHelper {

	private static final String TAG = "VkOAuthHelper";
	private static final String KEY_TOKEN = "token";
	private static final String VK_SHARED_PREFS = "vk_oauth_token";

	public static final String AUTORIZATION_URL = "http://oauth.vk.com/authorize?client_id=[YOUR_APP_ID]&scope=photos,messages,offline,friends,wall&redirect_uri=http://oauth.vk.com/blank.html&display=touch&response_type=token";
	
	private static final String REDIRECT = "http://oauth.vk.com/blank.html";
	
	public static void saveCredentials(Context ctx, String token) {
		Editor editor = ctx.getSharedPreferences(VK_SHARED_PREFS, Context.MODE_PRIVATE).edit();
		editor.putString(KEY_TOKEN, token);
		editor.commit();
	}
	
	public static String sign(Context ctx, String url) {
		SharedPreferences savedSession = ctx.getSharedPreferences(VK_SHARED_PREFS, Context.MODE_PRIVATE);
		if (url.indexOf("?") > 0) {
			return url + "&access_token=" + savedSession.getString(KEY_TOKEN, null);
		} else {
			return url + "?access_token=" + savedSession.getString(KEY_TOKEN, null);
		}
	}
	
	public static boolean isLogged(Context ctx) {
		SharedPreferences savedSession = ctx.getSharedPreferences(VK_SHARED_PREFS, Context.MODE_PRIVATE);
		return savedSession.getString(KEY_TOKEN, null) != null;
	}
	
	public static void exit(Context context) {
		// Edge case: an illegal state exception is thrown if an instance of
		// CookieSyncManager has not be created. CookieSyncManager is normally
		// created by a WebKit view, but this might happen if you start the
		// app, restore saved state, and click logout before running a UI
		// dialog in a WebView -- in which case the app crashes
		try{
			CookieSyncManager cookieSyncMngr = CookieSyncManager
					.createInstance(context);
			CookieManager cookieManager = CookieManager.getInstance();
			cookieManager.removeAllCookie();
		} catch (Exception e) {
			// TODO: handle exception
		}
		Editor editor = context.getSharedPreferences(VK_SHARED_PREFS, Context.MODE_PRIVATE)
				.edit();
		editor.clear();
		editor.commit();
	}
	
	public static boolean isRedirect(String url) {
		return url.startsWith(REDIRECT);
	}
	
	public static boolean proceedRedirectURL(final Activity context, String url, final Runnable success) {
		if (isRedirect(url)) {
			Uri parseUrl = Uri.parse(url);
			final String token = parseUrl.getFragment();
			if (token == null) {
				return false;
			}
			VkOAuthHelper.saveCredentials(context, token.split("=")[1]);
			if (success != null) {
				success.run();
			}
			return true;
		}
		return false;
	}
}
